package com.xiaoyu.lanling.feature.gift

import `in`.srain.cube.util.LocalDisplay
import android.app.Dialog
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.NonNull
import androidx.fragment.app.FragmentManager
import androidx.viewpager.widget.ViewPager
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.ErrorMessageEvent
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.model.User
import com.xiaoyu.base.utils.extensions.getViewTag
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.base.utils.extensions.setViewTag
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.BaseBottomSheetDialogFragment
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.event.gift.GiftListEvent
import com.xiaoyu.lanling.event.gift.GiftSelectEvent
import com.xiaoyu.lanling.event.gift.GiveGiftAndSendMessageEvent
import com.xiaoyu.lanling.feature.coin.activity.CoinRechargeDialogFragment
import com.xiaoyu.lanling.feature.gift.data.GiftData
import com.xiaoyu.lanling.feature.gift.fragment.NormalGiftFragment
import com.xiaoyu.lanling.feature.gift.model.Gift
import com.xiaoyu.lanling.view.FragmentAdapter
import com.xiaoyu.lanling.view.OnShowFragment
import com.xiaoyu.lanling.widget.tablayout.ScaleTabLayoutUtils
import kotlinx.android.synthetic.main.chat_gift_dialog.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.ArrayList

class ChatGiftBottomSheetDialog : BaseBottomSheetDialogFragment() {

    companion object {
        private val TAG: String = ChatGiftBottomSheetDialog::class.java.simpleName

        fun show(fragmentManager: FragmentManager, user: User, from: String) {
            val params = Bundle()
            params.putSerializable(Constant.IntentKey.KEY_USER, user)
            params.putString(Constant.PARAM_FROM, from)

            val dialogFragment = (fragmentManager.findFragmentByTag(TAG) as? BaseBottomSheetDialogFragment)
                    ?: ChatGiftBottomSheetDialog()
            dialogFragment.arguments = params
            dialogFragment.show(fragmentManager, TAG)
        }
    }

    private lateinit var fragmentAdapter: FragmentAdapter
    private val requestTag = Any()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.chat_gift_dialog, container, false)
    }

    override fun onViewCreatedSafelyAfterAppFinishInit(view: View, savedInstanceState: Bundle?) {
        super.onViewCreatedSafelyAfterAppFinishInit(view, savedInstanceState)
        initViewPager()
        initBind()
        initEvent()
        initData()
    }

    private fun initData() {
        val user = (arguments?.getSerializable(Constant.IntentKey.KEY_USER) as? User) ?: return
        val from = arguments?.getString(Constant.PARAM_FROM) ?: return
        GiftData.getGiftList(requestTag, user.uid, from)
    }

    @NonNull
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        dialog.setOnShowListener { dialogInterface ->
            val bottomSheetDialog = dialogInterface as? BottomSheetDialog
            setupFullHeight(bottomSheetDialog)
        }
        return dialog
    }

    private fun setupFullHeight(bottomSheetDialog: BottomSheetDialog?) {
        val bottomSheet = bottomSheetDialog?.findViewById<View>(R.id.design_bottom_sheet) as? FrameLayout
        bottomSheet?.let {
            val behavior = BottomSheetBehavior.from(it)
            it.layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT
            it.layoutParams = it.layoutParams
            behavior.peekHeight = LocalDisplay.SCREEN_HEIGHT_PIXELS
            behavior.state = BottomSheetBehavior.STATE_EXPANDED
            behavior.isHideable = true
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val view = view?.parent as View
        view.setBackgroundColor(Color.TRANSPARENT)
    }

    private fun initViewPager() {
        val titles: MutableList<CharSequence> = ArrayList()
        val fragmentList: MutableList<OnShowFragment> = ArrayList()

        titles.add(getString(R.string.gift_tab_normal_gift))
        fragmentList.add(NormalGiftFragment.create())

        fragmentAdapter = FragmentAdapter(childFragmentManager, fragmentList, titles)
        view_pager.offscreenPageLimit = fragmentList.size
        view_pager.adapter = fragmentAdapter
        view_pager.currentItem = 0
        view_pager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
            override fun onPageSelected(position: Int) {
                fragmentAdapter.tryShowOnIndex(position)
            }
        })

        ScaleTabLayoutUtils.createNormalNoScaleTabLayout(tab_layout, view_pager, titles)
    }

    private fun initBind() {
        send_button.setOnClickDebounceListener {
            val toUser = it.getViewTag<User>(Constant.GlobalViewTagDefine.VIEW_TAG_FOR_USER)
                    ?: return@setOnClickDebounceListener
            val gift = it.getViewTag<Gift>(Constant.GlobalViewTagDefine.VIEW_TAG_FOR_GIFT)
                    ?: return@setOnClickDebounceListener
            val from = arguments?.getString(Constant.PARAM_FROM)
                    ?: return@setOnClickDebounceListener

            GiftData.giveGift(requestTag, toUser.uid, gift.id, from)
            send_button.isEnabled = false
        }
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: GiftListEvent) {
                balance.text = event.coinBalance.toString()
                send_button.setViewTag(Constant.GlobalViewTagDefine.VIEW_TAG_FOR_USER, event.toUser)
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: GiveGiftAndSendMessageEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                if (isDetached) {
                    return
                }
                dismiss()
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: ErrorMessageEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                send_button.isEnabled = true
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: GiftSelectEvent) {
                send_button.setViewTag(Constant.GlobalViewTagDefine.VIEW_TAG_FOR_GIFT, event.item)
            }
        })
    }
}